<template>
  <view class="shopcart">
    <Address></Address>
    <Title></Title>
    <view class="goodBox" v-if="shopcartList.length">
      <uni-swipe-action>
        <block v-for="(item,index) in shopcartList" :key="item.goods_id">
          <uni-swipe-action-item :right-options="options" @click="handleClick($event,item)">
            <Good :good="item" @radioChange="radioChange">
              <template #default="{good}">
                <Count :good="good" @blur="changeGoodCount" @add="addGoodCount" @sub="subGoodCount"></Count>
              </template>
            </Good>
          </uni-swipe-action-item>
        </block>
      </uni-swipe-action>
      <NavBar></NavBar>
    </view>
    <view class="empty" v-else>
      <empty></empty>
    </view>
  </view>
</template>

<script>
import {mapState} from "vuex";
import Address from "@/pages/shopcart/components/Address/Address.vue";
import Title from "@/pages/shopcart/components/Title/Title.vue";
import Good from "@/pages/shopcart/components/Good/Good.vue";
import Count from "@/pages/shopcart/components/Count/Count.vue";
import NavBar from "@/pages/shopcart/components/NavBar/NavBar.vue";
import empty from "@/pages/shopcart/components/empty/empty.vue";
import setTabBarBadge from "@/mixin/setTabBarBadge";
import {setShopCartList} from "@/utils/authCartList";

export default {
  mixins: [setTabBarBadge],
  data() {
    return {
      options: [
        {
          text: '删除',
          style: {
            backgroundColor: '#c00000'
          }
        }
      ]
    };
  },
  methods: {
    /* 修改某一商品勾选状态的回调函数 */
    radioChange(good) {
      this.$store.dispatch("shopcartStore/changeGoodState", good)
    },
    /*  */
    changeGoodCount(good) {
      this.$store.dispatch("shopcartStore/changeGoodCount", good)
    },
    addGoodCount(good) {
      this.$store.dispatch("shopcartStore/addGoodCount", good)
    },
    subGoodCount(good) {
      if (good.goods_count < 1) return uni.showToast({title: "商品数量不能少于1", icon: "none", duration: 2000})
      this.$store.dispatch("shopcartStore/subGoodCount", good)
    },
    /* 点击选项按钮时触发事件 */
    handleClick(params, good) {
      if (params.index === 0) {
        // 点击的是删除按钮
        this.$store.dispatch("shopcartStore/deleteGood", good.goods_id)
      }
    }
  },
  computed: {
    ...mapState("shopcartStore", ["shopcartList"])
  },

  watch: {
    shopcartList: {
      handler(newValue, oldValue) {
        setShopCartList(newValue)
      },
      deep: true,
      immediate: true
    }
  },

  components: {
    Title,
    Address,
    Good,
    Count,
    NavBar,
    empty
  }

}
</script>

<style scoped lang="scss">
.goodBox{
  min-height: 1100rpx;
}
</style>
